package com.hsgene.dict.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.google.common.collect.Lists;
import com.hsgene.common.ClientType;
import com.hsgene.common.util.exception.GlobalExceptionHandler;
import com.hsgene.common.util.resolver.UserSessionArgResolver;
import com.hsgene.common.util.web.mapping.HsgeneRequestMappingHandlerMapping;
import com.hsgene.common.util.web.session.UserSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * MVC配置
 *
 * @author wangbing
 * @version 1.0, 2018/7/6
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    private String httpSessionEnable = "false";

    @Value("${global.exception.enable}")
    private String globalExceptionEnable;

    @Resource
    private RedisTemplate<String, UserSession> redisTemplate;

    @Override
    protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
        return new HsgeneRequestMappingHandlerMapping(Stream.of(ClientType.values()).map(ClientType::getCode).collect(Collectors.toList()));
    }

    @Override
    public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        RequestMappingHandlerAdapter adapter =  super.requestMappingHandlerAdapter();
        // 消息转换器
        adapter.setMessageConverters(Lists.newArrayList(getMessageConverter()));
        // 自定义注解@FromSession
        adapter.setCustomArgumentResolvers(Lists.newArrayList(getUserSessionArgResolver()));
        return adapter;
    }

    @Override
    protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        // 全局异常捕获配置
        exceptionResolvers.add(new GlobalExceptionHandler(isGlobalExceptionEnable()));
    }

    private boolean isGlobalExceptionEnable() {
        return Boolean.TRUE.toString().equalsIgnoreCase(globalExceptionEnable);
    }

    @Bean(name = "messageConverter")
    public MappingJackson2HttpMessageConverter getMessageConverter() {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        messageConverter.setPrettyPrint(Boolean.TRUE);
        messageConverter.setSupportedMediaTypes(Lists.newArrayList(MediaType.APPLICATION_JSON_UTF8));
        messageConverter.setObjectMapper(getObjectMapper());

        return messageConverter;
    }

    @Bean("objectMapper")
    public ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(getDateFormat());
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    @Bean("userSessionArgResolver")
    public UserSessionArgResolver getUserSessionArgResolver() {
        return new UserSessionArgResolver(redisTemplate, isHttpSessionEnable());
    }

    private boolean isHttpSessionEnable() {
        return Boolean.TRUE.toString().equalsIgnoreCase(httpSessionEnable);
    }

    public DateFormat getDateFormat() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
}
